//* ancestor of all aliens

function Alien() {
  // contructor
  this.frame = 0;
  this.life = 100;
  this.credit = 15;
  this.shrapnel = 3;
  this.x = Math.random()*640-320;
  this.y = Math.random()*480-240;
  this.strength = 5;
  this.kind = 0;
  this.max_speed = 2;
  this.dx = 0; 
  this.dy = 0; 
  this.images = null;
  this.color = 'rgba(255,0,255,1)';
  this.size = 16;
  this.angle = 0;

  // keep current direction
  this.simpleMove = function() {
    if (this.frame > alien_freeze_time) {
      this.x += this.dx;
      this.y += this.dy;
    }  
  }
 
  // update alien
  this.update = function() {
    // move alien
    simpleMove();
  }
  
  // keep them in given area
  this.constraint = function(ARange) {
    // keep dummies near earth
    if (this.x > ARange)  this.dx = -this.max_speed;
    if (this.x < -ARange) this.dx = +this.max_speed;
    if (this.y > ARange)  this.dy = -this.max_speed;
    if (this.y < -ARange) this.dy = +this.max_speed;
  }   

  // draw alien
  this.draw = function() {
    // update
    this.update();
    // drawing
    this.frame++;
    context.save();
    context.translate(-x0+this.x-ship.x,-y0+this.y-ship.y);
    context.rotate(this.angle);
    //context.fillStyle = "rgba(255,0,0,1)";
    //context.fillRect(-8,-8,16,16);
    if (this.images == null) {
      context.fillStyle = this.color;
      context.fillRect(-this.size/2,-this.size/2,this.size,this.size);
    } else
      this.images.draw(this.frame,-8,-8);
    context.restore();
  } 
}

function Aliens() {
  // create for array of aliens
  this.aliens = new Array();
  
  // add aliens of specific type
  this.add = function(AAliens) {
    for (var i=0; i<AAliens.length; i++)
      this.aliens.push(AAliens[i]);
  }
  
  // debug
  this.debug = function() {
    var s = 'alines: '+this.aliens.length+'\n';
    for (var i=0; i<this.aliens.length; i++)
      s += 'aliens['+i+']: kind='+this.aliens[i].kind+' x='+this.aliens[i].x+' y='+this.alienss[i].y+'\n';
    return s+'\n';      
  }
  
  // draw all aliens at once
  this.draw = function() {
    for (var i=0; i<this.aliens.length; i++) {
      // draw aliens
      this.aliens[i].draw();
      // too close aliens suck life from ship
      var close = (Math.abs(this.aliens[i].x-ship.x) < 16) && (Math.abs(this.aliens[i].y-ship.y) < 16);
      if (close) {
        var oldlife = ship.life;
        ship.life -= this.aliens[i].strength;
        if ( (ship.life <= 0)&&(oldlife > 0) ) {
          credits.explode(ship.x,ship.y,Math.min(500,ship.credit+10)); // limit size of ship explosion to 500 for performance reason
          score();
        }
        if (ship.life < 0)
          ship.life = 0;
      }
    }
  }
}
